//
// Created by yhy on 17-6-26.
//

#ifndef UNTITLED2_MYHANDLER_H
#define UNTITLED2_MYHANDLER_H

#include <iostream>
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketNotification.h"
#include "Poco/Observer.h"
#include "SingletonCheckTimeoutNotification.h"
#include "MyReactor.h"
#include <Poco/NObserver.h>
#include <Poco/Net/SocketReactor.h>



using namespace Poco;
class MyHandler {

public:
    MyHandler(Net::StreamSocket& socket, Net::SocketReactor& reactor):
            _socket(socket),
            _reactor(reactor){
        addEvent();
    }

    ~MyHandler(){
        removeEvent();
    }

private:
    void onReadable(Net::ReadableNotification* pNf);

    void onTimeout(Net::TimeoutNotification* pNf);

    void onSingletonTimeout(const AutoPtr<SingletonCheckTimeoutNotification>& timeoutEvent );

private:
    //添加事件
    void addEvent(){
        _reactor.addEventHandler(_socket, Observer<MyHandler, Net::ReadableNotification>(*this, &MyHandler::onReadable));
        _reactor.addEventHandler(_socket, Observer<MyHandler, Net::TimeoutNotification>(*this, &MyHandler::onTimeout));
        MyReactor* p = (MyReactor *) &_reactor;
        p->addTimeoutHandler(NObserver<MyHandler,SingletonCheckTimeoutNotification>(*this,&MyHandler::onSingletonTimeout));
    }

    //删除事件
    void removeEvent(){
        _reactor.removeEventHandler(_socket, Observer<MyHandler, Net::ReadableNotification>(*this, &MyHandler::onReadable));
        _reactor.removeEventHandler(_socket, Observer<MyHandler, Net::TimeoutNotification>(*this, &MyHandler::onTimeout));
        MyReactor* p = (MyReactor *) &_reactor;
        p->removeTimeoutHandler(NObserver<MyHandler,SingletonCheckTimeoutNotification>(*this,&MyHandler::onSingletonTimeout));
    }



private:
    Net::StreamSocket   _socket;
    Net::SocketReactor& _reactor;
    time_t lastUpdate;
};


#endif //UNTITLED2_MYHANDLER_H
